package com.bear.atlassianmcp.confluence.mcp.tools;

import com.bear.atlassianmcp.confluence.model.ConfluenceComment;
import com.bear.atlassianmcp.confluence.model.ConfluenceLabel;
import com.bear.atlassianmcp.confluence.model.ConfluencePage;
import com.bear.atlassianmcp.confluence.service.ConfluenceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Confluence高级管理MCP工具
 * 提供页面、评论、标签的综合管理功能
 */
@Service
public class ConfluenceAdvancedTools {

    private static final Logger logger = LoggerFactory.getLogger(ConfluenceAdvancedTools.class);

    private final ConfluenceService confluenceService;

    @Autowired
    public ConfluenceAdvancedTools(ConfluenceService confluenceService) {
        this.confluenceService = confluenceService;
    }

    /**
     * 获取页面完整信息（包括评论和标签）
     * 
     * @param pageId 页面ID
     * @return 页面完整信息的格式化文本
     */
    // @Tool(description = "获取Confluence页面的完整信息，包括页面内容、评论列表和标签列表")
    public String getPageFullInfo(String pageId, ToolContext toolContext) {
        logger.info("MCP Tool: Getting full info for Confluence page {}", pageId);
        
        try {
            StringBuilder result = new StringBuilder();
            
            // 获取页面基本信息
            ConfluencePage page = confluenceService.getPageContent(pageId, toolContext);
            result.append("📄 页面完整信息：\n");
            result.append("═".repeat(50)).append("\n\n");
            result.append(page.toFormattedString());
            
            // 获取页面标签
            try {
                List<ConfluenceLabel> labels = confluenceService.getPageLabels(pageId, toolContext);
                result.append("\n🏷️ 页面标签 (共").append(labels.size()).append("个)：\n");
                if (labels.isEmpty()) {
                    result.append("   暂无标签\n");
                } else {
                    for (ConfluenceLabel label : labels) {
                        result.append("   • ").append(label.getName()).append("\n");
                    }
                }
            } catch (Exception e) {
                result.append("\n🏷️ 页面标签：获取失败 - ").append(e.getMessage()).append("\n");
            }
            
            // 获取页面评论
            try {
                List<ConfluenceComment> comments = confluenceService.getPageComments(pageId, 5, toolContext);
                result.append("\n💬 页面评论 (共").append(comments.size()).append("条，显示最近5条)：\n");
                if (comments.isEmpty()) {
                    result.append("   暂无评论\n");
                } else {
                    for (int i = 0; i < Math.min(5, comments.size()); i++) {
                        ConfluenceComment comment = comments.get(i);
                        result.append("   ").append(i + 1).append(". ");
                        if (comment.getCreatedBy() != null) {
                            result.append(comment.getCreatedBy()).append(" ");
                        }
                        if (comment.getCreatedDate() != null) {
                            result.append("(").append(comment.getCreatedDate()).append(")");
                        }
                        result.append("\n");
                        
                        String content = comment.getContent();
                        if (content != null && !content.trim().isEmpty()) {
                            String preview = content.length() > 100 ? content.substring(0, 100) + "..." : content;
                            result.append("      📝 ").append(preview).append("\n");
                        }
                    }
                }
            } catch (Exception e) {
                result.append("\n💬 页面评论：获取失败 - ").append(e.getMessage()).append("\n");
            }
            
            // 获取子页面
            try {
                List<ConfluencePage> childPages = confluenceService.getChildPages(pageId, 5, toolContext);
                result.append("\n📁 子页面 (共").append(childPages.size()).append("个，显示最近5个)：\n");
                if (childPages.isEmpty()) {
                    result.append("   暂无子页面\n");
                } else {
                    for (int i = 0; i < Math.min(5, childPages.size()); i++) {
                        ConfluencePage child = childPages.get(i);
                        result.append("   ").append(i + 1).append(". ").append(child.getTitle());
                        result.append(" (ID: ").append(child.getId()).append(")\n");
                    }
                }
            } catch (Exception e) {
                result.append("\n📁 子页面：获取失败 - ").append(e.getMessage()).append("\n");
            }
            
            logger.info("Successfully retrieved full info for Confluence page {} via MCP", pageId);
            return result.toString();
            
        } catch (Exception e) {
            logger.error("Failed to get full info for Confluence page {} via MCP: {}", pageId, e.getMessage());
            return "❌ 获取页面完整信息失败。原因：" + e.getMessage();
        }
    }

    /**
     * 创建页面并添加标签
     * 
     * @param title 页面标题
     * @param content 页面内容
     * @param spaceKey 空间键值
     * @param parentId 父页面ID（可选）
     * @param labels 标签列表，用逗号分隔（可选）
     * @return 创建结果的格式化文本
     */
    // @Tool(description = "创建Confluence页面并同时添加标签")
    public String createPageWithLabels(String title, String content, String spaceKey, String parentId, String labels, ToolContext toolContext) {
        logger.info("MCP Tool: Creating Confluence page '{}' with labels in space '{}'", title, spaceKey);
        
        try {
            // 创建页面
            ConfluencePage page = confluenceService.createPage(title, content, spaceKey, parentId, toolContext);
            
            StringBuilder result = new StringBuilder();
            result.append("✅ 页面创建成功！\n\n");
            result.append(page.toFormattedString());
            
            // 添加标签（如果提供）
            if (labels != null && !labels.trim().isEmpty()) {
                result.append("\n🏷️ 添加标签：\n");
                String[] labelArray = labels.split(",");
                int successCount = 0;
                
                for (String labelName : labelArray) {
                    String trimmedLabel = labelName.trim();
                    if (!trimmedLabel.isEmpty()) {
                        try {
                            confluenceService.addLabel(page.getId(), trimmedLabel, toolContext);
                            result.append("   ✅ ").append(trimmedLabel).append(" - 添加成功\n");
                            successCount++;
                        } catch (Exception e) {
                            result.append("   ❌ ").append(trimmedLabel).append(" - 添加失败: ").append(e.getMessage()).append("\n");
                        }
                    }
                }
                
                result.append(String.format("\n📊 标签添加结果: 成功 %d 个", successCount));
            }
            
            logger.info("Successfully created Confluence page '{}' with labels via MCP", title);
            return result.toString();
            
        } catch (Exception e) {
            logger.error("Failed to create Confluence page '{}' with labels via MCP: {}", title, e.getMessage());
            return "❌ 创建页面失败。原因：" + e.getMessage();
        }
    }

    /**
     * 页面内容搜索和替换
     * 
     * @param pageId 页面ID
     * @param searchText 要搜索的文本
     * @param replaceText 替换的文本
     * @return 搜索替换结果的格式化文本
     */
    @Tool(description = "在Confluence页面内容中搜索并替换指定文本")
    public String searchAndReplacePageContent(String pageId, String searchText, String replaceText, ToolContext toolContext) {
        logger.info("MCP Tool: Search and replace in Confluence page {}", pageId);
        
        try {
            // 获取当前页面内容
            ConfluencePage page = confluenceService.getPageContent(pageId, toolContext);
            String currentContent = page.getContent();
            
            if (currentContent == null || currentContent.trim().isEmpty()) {
                return "❌ 页面内容为空，无法进行搜索替换。";
            }
            
            // 检查是否包含搜索文本
            if (!currentContent.contains(searchText)) {
                return String.format("🔍 在页面内容中未找到文本: '%s'", searchText);
            }
            
            // 执行替换
            String newContent = currentContent.replace(searchText, replaceText);

            // 计算替换次数
            int replaceCount = 0;
            if (searchText.length() != replaceText.length()) {
                replaceCount = (currentContent.length() - newContent.length()) / (searchText.length() - replaceText.length());
            } else {
                // 当搜索文本和替换文本长度相同时，通过计算出现次数来确定替换次数
                String temp = currentContent;
                while (temp.contains(searchText)) {
                    replaceCount++;
                    temp = temp.replaceFirst(java.util.regex.Pattern.quote(searchText), "");
                }
            }
            
            // 更新页面
            Integer currentVersion = page.getVersion() != null ? page.getVersion().getNumber() : 1;
            ConfluencePage updatedPage = confluenceService.updatePage(
                pageId, 
                page.getTitle(), 
                newContent, 
                currentVersion + 1,
                    toolContext
            );
            
            StringBuilder result = new StringBuilder();
            result.append("✅ 搜索替换完成！\n\n");
            result.append(String.format("🔍 搜索文本: '%s'\n", searchText));
            result.append(String.format("🔄 替换文本: '%s'\n", replaceText));
            result.append(String.format("📊 替换次数: %d\n\n", replaceCount));
            result.append("📄 更新后的页面信息：\n");
            result.append(updatedPage.toFormattedString());
            
            logger.info("Successfully performed search and replace in Confluence page {} via MCP", pageId);
            return result.toString();
            
        } catch (Exception e) {
            logger.error("Failed to perform search and replace in Confluence page {} via MCP: {}", pageId, e.getMessage());
            return "❌ 搜索替换失败。原因：" + e.getMessage();
        }
    }
}
